package com.gadgets.framework.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;

/**
 * @author UncleXiu
 * @version V1.0.0
 * @data 2020-09-15
 *
 */
public class PropertiesUtils {

    private static final HashMap<String,Properties> PROPERTIES_MAP = new HashMap<>();

    /**
     * 通过文件流获取Properties
     * @param inputStream   文件流
     * @return              属性集合
     * @throws IOException  I/O异常
     */
    public static Properties getProperty(InputStream inputStream) throws IOException {
        Properties properties = new Properties();
        properties.load(inputStream);
        return properties;
    }

    /**
     * 通过文件流获取Properties
     * @param file          文件
     * @return              属性集合
     */
    public static Properties getProperty(File file) throws IOException {
        Properties properties = new Properties();
        InputStream inputStream = new FileInputStream(file);
        properties.load(inputStream);
        return properties;
    }

    /**
     * 获取 properties 文件对应的属性名
     * @param path          属性文件路径
     * @param key           属性key
     * @return              属性value
     * @throws IOException  I/O异常
     */
    public static String getPropertyByValue(String path, Object key) throws IOException {
        if(!PROPERTIES_MAP.containsKey(path)) {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
            if (null == inputStream) {
                return null;
            }
            Properties properties = new Properties();
            properties.load(inputStream);
            PROPERTIES_MAP.put(path, properties);
        }
        Properties properties = PROPERTIES_MAP.get(path);
        return properties.get(key).toString();
    }

}
